import router from '~/router';
import store from '~/state';

function Response (xml) {
    if (!xml.response) {
        this.data = {};
    } else if (typeof xml.response == 'string') {
        this.data  = JSON.parse(xml.response);
    } else {
        this.data  = xml.response;
    }
    
    this.status = xml.status;
    this.statusText = xml.statusText;
    this.headers = {};

    var headersArr = xml.getAllResponseHeaders().split('\n');
    for (var k in headersArr) {
        var header = headersArr[k].split(': ');
        var name = header[0];
        var value = header[1];
        this.headers[name] = value;
    }
}
var Api = {
    defaults:{
        baseURL: '/api/',
        timeout: 5000,
        headers: {
            'X-Requested-With': 'xmlhttprequest'
        }
    },
    xml: null
};

Api.get = function (url) {
    this.xml = new XMLHttpRequest();
    this.xml.open('get', this.defaults.baseURL+url);
    
    return this;
};

Api.post = function (url, data) {
    if(!data)
        data = {};
    this.xml = new XMLHttpRequest();
    this.xml.open('post', this.defaults.baseURL+url);
    this.method = 'post';
    this.xml.data = data;

    return this;
};

Api.then = function (call) {
    var xml = this.xml;
    var api = this;
    for(var k in this.defaults.headers) {
        xml.setRequestHeader(k, this.defaults.headers[k]);
    }
    if (store.state.access_token != null) {
        xml.setRequestHeader('Authorization', 'Bearer '+store.state.access_token.access_token);
    }
    xml.timeout = this.defaults.timeout;
    xml.onreadystatechange = function () {
        if (this.readyState != 4) {
            return;
        }
        if (this.status == 200) {
            var response = new Response(xml);
            call(response);
        } else if (this.status == 401) {
            // alert('登录过期');
            store.commit('logout');
            // router.push('/auth/login');
            window.location = '/api/login/wechat';
            return ;
        } else if (this.status == 422) {
            this.err = JSON.parse(this.responseText).error;
        }
    };
    var formData = null;
    if (this.method == 'post') {
        formData = new FormData();
        var data = this.xml.data;
        if (typeof data == 'string') {
            this.xml.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            formData = data;
        } else {
            for(k in data) {
                formData.append(k, data[k]);
            }
        }
    }

    xml.send(formData);

    return this;
};

Api.catch = function (call) {
    var xml = this.xml;
    var base = this.xml.onreadystatechange;
    this.xml.onreadystatechange = function () {
        if (this.readyState!=4) {
            return;
        }
        base.apply(xml);
        if(typeof base == 'function' && this.status != 200) {
            call(xml);
        }
    };
};

export default Api;